package top.ezzz.tool;

import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.exception.StatusException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;

@Slf4j
@Component
public class ProcessFilter implements Filter {
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        //1.开始计时（用于计算响应时长）
        long start = System.currentTimeMillis();
        try {
            chain.doFilter(ctx);
        } catch (StatusException e) {
            //2.状态异常，一般是 4xx 错误
            ctx.status(e.getCode());
        } catch (Throwable e) {
            //3.异常捕促与控制
            ctx.status(500);
            log.error(e.getMessage());
        }
        //4.获得接口响应时长
        long times = System.currentTimeMillis() - start;
        log.info("请求地址：{}，参数：{} ，用时：{}", ctx.path(), ctx.paramMap(), times);
    }
}